package com.fastplatform.specification;

import com.fastplatform.entity.User;
import com.fastplatform.entity.User_;
import org.springframework.data.jpa.domain.Specification;
import jakarta.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

public class UserSpecification {
    
    /**
     * 根据条件查找用户列表（使用JPA Criteria Queries和元数据）
     */
    public static Specification<User> findUsersByConditions(String username, String phone, Integer status, String userType) {
        return (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            
            // 基础条件：未删除
            predicates.add(criteriaBuilder.equal(root.get(User_.deleted), false));
            
            // 用户名模糊查询
            if (username != null && !username.trim().isEmpty()) {
                predicates.add(criteriaBuilder.like(root.get(User_.username), "%" + username + "%"));
            }
            
            // 手机号模糊查询
            if (phone != null && !phone.trim().isEmpty()) {
                predicates.add(criteriaBuilder.like(root.get(User_.phone), "%" + phone + "%"));
            }
            
            // 状态精确查询
            if (status != null) {
                predicates.add(criteriaBuilder.equal(root.get(User_.status), status));
            }
            
            // 用户类型精确查询
            if (userType != null && !userType.trim().isEmpty()) {
                predicates.add(criteriaBuilder.equal(root.get(User_.userType), userType));
            }
            
            // 排序
            query.orderBy(criteriaBuilder.desc(root.get(User_.createTime)));
            
            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };
    }
}